package org.linlinjava.litemall.admin.service;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import me.chanjar.weixin.common.error.WxErrorException;
import org.linlinjava.litemall.core.util.bcrypt.MessageSubscribeUtil;
import org.linlinjava.litemall.db.domain.LitemallArrivalReminder;
import org.linlinjava.litemall.db.domain.LitemallBookReview;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallArrivalReminderService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author piao
 * @Date 2021/03/19
 */
@Service
public class AdminArrivalReminderService {
    @Autowired
    private MessageSubscribeUtil messageSubscribeUtil;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallArrivalReminderService arrivalReminderService;

    public void sendArrivalRemind(LitemallArrivalReminder arrivalReminder) {
        arrivalReminder.setDeleted(true);
        arrivalReminderService.update(arrivalReminder);
        Integer userId = arrivalReminder.getUserId();
        LitemallUser user = userService.findById(userId);
        String openid = user.getWeixinOpenid();
        String templateId = "YavxVD7qEtPSCEbDrYUeENHmMZUJv7xq1adtagG2pVw";
        String page = "pages/index/index";
        List<WxMaSubscribeMessage.Data> data = new ArrayList<>();

        WxMaSubscribeMessage.Data data1 = new WxMaSubscribeMessage.Data();
        data1.setName("thing1");
        data1.setValue(arrivalReminder.getBookName());
        data.add(data1);

        WxMaSubscribeMessage.Data data2 = new WxMaSubscribeMessage.Data();
        data2.setName("time3");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String strNow = dtf.format(LocalDateTime.now());
        data2.setValue(strNow);
        data.add(data2);
        try {
            messageSubscribeUtil.sendSubscribeMsg(openid, templateId, data, page);
        } catch (WxErrorException e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }
}
